// page/component/category/category.js
const { request } = require('../../../utils/request');
Page({
  data: {
    category: [],
    detail: [],
    curIndex: 0,
    isScoll: false,
    toView: '',
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    productQuantities: {} // 存储每个商品的数量
  },

  onLoad: function (options) {
    this.fetchCategories();
  },

  fetchCategories() {
    request({
      url: '/category',
      method: 'GET'
    })
    .then((res) => {
      if (res.code === 2000) {
        const category = res.data;
        this.setData({
          category,
          toView: category[0]?.id || '',
          curIndex: 0
        });
        this.fetchProducts(category[0]?.id);
      } else {
        console.error('获取分类数据失败:', res.message);
      }
    })
    .catch((error) => {
      console.error('请求分类接口出错:', error);
    });
  },

  fetchProducts(categoryId, isRefresh = false) {
    if (this.data.loading || !this.data.hasMore && !isRefresh) return;

    this.setData({
      loading: true
    });

    const page = isRefresh ? 1 : this.data.page;

    request({
      url: '/product',
      method: 'GET',
      data: {
        category_id: categoryId,
        page,
        page_size: this.data.pageSize
      }
    })
    .then((res) => {
      console.log('Product API 响应数据:', res); // 打印接口响应数据
      if (res.code === 2000) {
        const newDetail = isRefresh ? res.data.items : [...this.data.detail, ...res.data.items];
        const hasMore = res.data.items.length >= this.data.pageSize;

        this.setData({
          detail: newDetail,
          page,
          hasMore,
          loading: false
        }, () => {
          console.log('setData 后的 detail 数据:', this.data.detail); // 打印更新后的数据
        });

        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      } else {
        console.error('获取商品数据失败:', res.message);
        this.setData({
          loading: false
        });
      }
    })
    .catch((error) => {
      console.error('请求商品接口出错:', error);
      this.setData({
        loading: false
      });
    });
  },

  switchTab(e) {
    const { id, index } = e.currentTarget.dataset;
    // 当点击不同分类时，重置页码、加载状态和是否有更多数据
    if (this.data.curIndex !== index) {
      this.setData({
        curIndex: index,
        toView: id,
        page: 1,
        hasMore: true,
        detail: [] // 清空当前商品列表
      }, () => {
        this.fetchProducts(id, true); // 刷新商品列表
      });
    }
  },

  onPullDownRefresh: function () {
    const currentCategory = this.data.category[this.data.curIndex];
    if (currentCategory) {
      this.fetchProducts(currentCategory.id, true);
    }
  },

  onReachBottom: function () {
    const currentCategory = this.data.category[this.data.curIndex];
    if (currentCategory && this.data.hasMore) {
      this.setData({
        page: this.data.page + 1
      });
      this.fetchProducts(currentCategory.id);
    }
  },


// 减少商品数量
decreaseQuantity(e) {
  const productId = e.currentTarget.dataset.id;
  const productQuantities = { ...this.data.productQuantities };
  if (productQuantities[productId] && productQuantities[productId] > 1) {
    productQuantities[productId]--;
    this.setData({ productQuantities });
  }
},

// 增加商品数量
increaseQuantity(e) {
  const productId = e.currentTarget.dataset.id;
  const productQuantities = { ...this.data.productQuantities };
  productQuantities[productId] = (productQuantities[productId] || 0) + 1;
  this.setData({ productQuantities });
},

// 获取商品当前数量
getQuantity(productId) {
  return this.data.productQuantities[productId] || 1;
},

// 加入购物车
addToCart(e) {
  const productId = e.currentTarget.dataset.id;
  const productQuantities = this.data.productQuantities;
  const quantity = productQuantities[productId] || 1; // 获取商品数量，若未设置则默认为 1
  const product = this.data.detail.find(item => item.id === productId);

  if (product) {
    const cartItem = {
      product_id: product.id,
      quantity: quantity, // 将商品数量添加到请求数据中
    };

    // 调用接口添加商品到购物车
    wx.showLoading({
      title: '添加中...',
    });
    request({
      url: '/cart',
      method: 'POST',
      data: cartItem
    })
    .then((res) => {
      wx.hideLoading();
      if (res.code === 2000) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
        // 添加成功后，将对应商品数量置为 1
        const newProductQuantities = { ...productQuantities };
        newProductQuantities[productId] = 1;
        this.setData({
          productQuantities: newProductQuantities
        });
      } else {
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
        console.error('添加商品到购物车失败:', res.message);
      }
    })
    .catch((error) => {
      wx.hideLoading();
      wx.showToast({
        title: '请求出错',
        icon: 'none'
      });
      console.error('添加商品到购物车请求出错:', error);
    });
  }
},
});
